<?php
/**
 * Created by PhpStorm.
 * User: yangchunrun
 * Date: 17/3/20
 * Time: 下午11:22
 */
function getremotefile($file) {
    global $_G;
    @set_time_limit(0);
    if(!@readfile($_G['setting']['ftp']['attachurl'].'forum/'.$file)) {
        $ftp = ftpcmd('object');
        $tmpfile = @tempnam($_G['setting']['attachdir'], '');
        if($ftp->ftp_get($tmpfile, 'forum/'.$file, FTP_BINARY)) {
            @readfile($tmpfile);
            @unlink($tmpfile);
        } else {
            @unlink($tmpfile);
            return FALSE;
        }
    }
    return TRUE;
}

function getlocalfile($filename, $readmod = 2, $range = 0) {
    if($readmod == 1 || $readmod == 3 || $readmod == 4) {
        if($fp = @fopen($filename, 'rb')) {
            @fseek($fp, $range);
            if(function_exists('fpassthru') && ($readmod == 3 || $readmod == 4)) {
                @fpassthru($fp);
            } else {
                echo @fread($fp, filesize($filename));
            }
        }
        @fclose($fp);
    } else {
        @readfile($filename);
    }
    @flush(); @ob_flush();
}

function attachment_updateviews($logfile) {
    $viewlog = $viewarray = array();
    $newlog = DISCUZ_ROOT.$logfile.random(6);
    if(@rename(DISCUZ_ROOT.$logfile, $newlog)) {
        $viewlog = file($newlog);
        unlink($newlog);
        if(is_array($viewlog) && !empty($viewlog)) {
            $viewlog = array_count_values($viewlog);
            foreach($viewlog as $id => $views) {
                if($id > 0) {
                    $viewarray[$views][] = intval($id);
                }
            }
            foreach($viewarray as $views => $ids) {
                C::t('forum_attachment')->update_download($ids, $views);
            }
        }
    }
}
$splugin_setting = $_G['cache']['plugin']['thinker_wx'];
$free_credits_limit = $splugin_setting['free_credits_limit'];
$qrcode_exprie = $splugin_setting['qrcode_exprie'];

if ($_POST) {
    $uid = $_POST['uid'];
    $aid = $_POST['a_id'];
    $code1 = $_POST['code1'];
    $code2 = $_POST['code2'];
    $pay_href = $_POST['payUrl'];
    $need_pay = $_POST['need_pay'];
    $is_free = $_POST['is_free'];
    $tableid = 'aid:'.$aid;


    if (!$code2) {
        showmessage('请输入验证码!', '', array(), array('showdialog' => 1, 'showmsg' => true, 'closetime' => true));
    }
    $time = time() - $qrcode_exprie;
    $row = C::t('#thinker_wx#common_attach_qrcode')->fetch("uid=$uid and aid = $aid and code1 ='{$code1}' and code2 = '{$code2}' and createtime > '$time' and status = 0");
    if (!$row) {
        showmessage('验证码不正确或者已过期!', '', array(), array('showdialog' => 1, 'showmsg' => true, 'closetime' => true));
//        echo "<script>alert('验证码不正确或者已过期!');</script>";
//        die('ajaxerror');
    } else {
        C::t('#thinker_wx#common_attach_qrcode')->update_by_where(array('status' => 2), "uid=$uid and aid = $aid and code1 ='{$code1}' and code2 = '{$code2}'");
        if ($is_free==0)//Need Pay
        {
            echo "<script>parent.location.href='$pay_href';</script>";
        } else {


            //$attach = C::t('forum_attachment_n')->fetch($tableid, $a_id);
            if($_G['setting']['attachexpire']) {

                if(TIMESTAMP - $t > $_G['setting']['attachexpire'] * 3600) {
                    $aid = intval($aid);
                    if($attach = C::t('forum_attachment_n')->fetch($tableid, $aid)) {
                        if($attach['isimage']) {
                            dheader('location: '.$_G['siteurl'].'static/image/common/none.gif');
                        } else {
                            if(!$requestmode) {
                                showmessage('attachment_expired', '', array('aid' => aidencode($aid, 0, $attach['tid']), 'pid' => $attach['pid'], 'tid' => $attach['tid']));
                            } else {
                                exit;
                            }
                        }
                    } else {
                        if(!$requestmode) {
                            showmessage('attachment_nonexistence');
                        } else {
                            exit;
                        }
                    }
                }
            }

            $readmod = getglobal('config/download/readmod');
            $readmod = $readmod > 0 && $readmod < 5 ? $readmod : 2;

            $refererhost = parse_url($_SERVER['HTTP_REFERER']);
            $serverhost = $_SERVER['HTTP_HOST'];
            if(($pos = strpos($serverhost, ':')) !== FALSE) {
                $serverhost = substr($serverhost, 0, $pos);
            }

            if(!$requestmode && $_G['setting']['attachrefcheck'] && $_SERVER['HTTP_REFERER'] && !($refererhost['host'] == $serverhost)) {
                showmessage('attachment_referer_invalid', NULL);
            }

            periodscheck('attachbanperiods');

            loadcache('threadtableids');
            $threadtableids = !empty($_G['cache']['threadtableids']) ? $_G['cache']['threadtableids'] : array();
            if(!in_array(0, $threadtableids)) {
                $threadtableids = array_merge(array(0), $threadtableids);
            }
            $archiveid = in_array($_GET['archiveid'], $threadtableids) ? intval($_GET['archiveid']) : 0;




            $attachexists = FALSE;
            if(!empty($aid) && is_numeric($aid)) {
                $attach = C::t('forum_attachment_n')->fetch($tableid, $aid);
                $thread = C::t('forum_thread')->fetch_by_tid_displayorder($attach['tid'], 0, '>=', null, $archiveid);
                if($_G['uid'] && $attach['uid'] != $_G['uid']) {
                    if($attach) {
                        $attachpost = C::t('forum_post')->fetch($thread['posttableid'], $attach['pid'], false);
                        $attach['invisible'] = $attachpost['invisible'];
                        unset($attachpost);
                    }
                    if($attach && $attach['invisible'] == 0) {
                        $thread && $attachexists = TRUE;
                    }
                } else {
                    $attachexists = TRUE;
                }
            }

            if(!$attachexists) {
                if(!$requestmode) {
                    showmessage('attachment_nonexistence');
                } else {
                    exit;
                }
            }

            if(!$requestmode) {
                $forum = C::t('forum_forumfield')->fetch_info_for_attach($thread['fid'], $_G['uid']);

                $_GET['fid'] = $forum['fid'];

                if($attach['isimage']) {
                    $allowgetattach = !empty($forum['allowgetimage']) || (($_G['group']['allowgetimage'] || $_G['uid'] == $attach['uid']) && !$forum['getattachperm']) || forumperm($forum['getattachperm']);
                } else {
                    $allowgetattach = !empty($forum['allowgetattach']) || (($_G['group']['allowgetattach']  || $_G['uid'] == $attach['uid']) && !$forum['getattachperm']) || forumperm($forum['getattachperm']);
                }
                if($allowgetattach && ($attach['readperm'] && $attach['readperm'] > $_G['group']['readaccess']) && $_G['adminid'] <= 0 && !($_G['uid'] && $_G['uid'] == $attach['uid'])) {
                    showmessage('attachment_forum_nopermission', NULL, array(), array('login' => 1));
                }

                $ismoderator = in_array($_G['adminid'], array(1, 2)) ? 1 : ($_G['adminid'] == 3 ? C::t('forum_moderator')->fetch_uid_by_tid($attach['tid'], $_G['uid'], $archiveid) : 0);

                $ispaid = FALSE;
                $exemptvalue = $ismoderator ? 128 : 16;
                if(!$thread['special'] && $thread['price'] > 0 && (!$_G['uid'] || ($_G['uid'] != $attach['uid'] && !($_G['group']['exempt'] & $exemptvalue)))) {
                    if(!$_G['uid'] || $_G['uid'] && !($ispaid = C::t('common_credit_log')->count_by_uid_operation_relatedid($_G['uid'], 'BTC', $attach['tid']))) {
                        showmessage('attachment_payto', 'forum.php?mod=viewthread&tid='.$attach['tid']);
                    }
                }

            }

            $isimage = $attach['isimage'];
            $_G['setting']['ftp']['hideurl'] = $_G['setting']['ftp']['hideurl'] || ($isimage && !empty($_GET['noupdate']) && $_G['setting']['attachimgpost'] && strtolower(substr($_G['setting']['ftp']['attachurl'], 0, 3)) == 'ftp');

            if(empty($_GET['nothumb']) && $attach['isimage'] && $attach['thumb']) {
                $db = DB::object();
                $db->close();
                !$_G['config']['output']['gzip'] && ob_end_clean();
                dheader('Content-Disposition: inline; filename='.getimgthumbname($attach['filename']));
                dheader('Content-Type: image/pjpeg');
                if($attach['remote']) {
                    $_G['setting']['ftp']['hideurl'] ? getremotefile(getimgthumbname($attach['attachment'])) : dheader('location:'.$_G['setting']['ftp']['attachurl'].'forum/'.getimgthumbname($attach['attachment']));
                } else {
                    getlocalfile($_G['setting']['attachdir'].'/forum/'.getimgthumbname($attach['attachment']));
                }
                exit();
            }

            $filename = $_G['setting']['attachdir'].'/forum/'.$attach['attachment'];
            if(!$attach['remote'] && !is_readable($filename)) {
                $storageService = Cloud::loadClass('Service_Storage');
                $storageService->checkAttachment($attach);
                if(!$requestmode) {
                    showmessage('attachment_nonexistence');
                } else {
                    exit;
                }
            }


//            if(!$requestmode) {
//                if(!$ispaid && !$forum['allowgetattach']) {
//                    if(!$forum['getattachperm'] && !$allowgetattach) {
//                        showmessage('getattachperm_none_nopermission', NULL, array(), array('login' => 1));
//                    } elseif(($forum['getattachperm'] && !forumperm($forum['getattachperm'])) || ($forum['viewperm'] && !forumperm($forum['viewperm']))) {
//                        showmessagenoperm('getattachperm', $forum['fid']);
//                    }
//                }
//
//                $exemptvalue = $ismoderator ? 32 : 4;
//                if(!$isimage && !($_G['group']['exempt'] & $exemptvalue)) {
//                    $creditlog = updatecreditbyaction('getattach', $_G['uid'], array(), '', 1, 0, $thread['fid']);
//                    if($creditlog['updatecredit']) {
//                        if($_G['uid']) {
//                            $k = $_GET['ck'];
//                            $t = $_GET['t'];
//                            if(empty($k) || empty($t) || $k != substr(md5($aid.$t.md5($_G['config']['security']['authkey'])), 0, 8) || TIMESTAMP - $t > 3600) {
//                                $url = 'forum.php?mod=misc&action=attachcredit&aid='.$attach['aid'].'&formhash='.FORMHASH;
//                                echo "<script>parent.location.href='$url';</script>";
//                                //dheader('location: forum.php?mod=misc&action=attachcredit&aid='.$attach['aid'].'&formhash='.FORMHASH);
//                                exit();
//                            }
//                        } else {
//                            showmessage('attachment_forum_nopermission', NULL, array(), array('login' => 1));
//                        }
//                    }
//                }
//
//            }

            $range = 0;
            if($readmod == 4 && !empty($_SERVER['HTTP_RANGE'])) {
                list($range) = explode('-',(str_replace('bytes=', '', $_SERVER['HTTP_RANGE'])));
            }

            if(!$requestmode && !$range && empty($_GET['noupdate'])) {
                if($_G['setting']['delayviewcount']) {
                    $_G['forum_logfile'] = './data/cache/forum_attachviews_'.intval(getglobal('config/server/id')).'.log';
                    if(substr(TIMESTAMP, -1) == '0') {
                        attachment_updateviews($_G['forum_logfile']);
                    }

                    if(@$fp = fopen(DISCUZ_ROOT.$_G['forum_logfile'], 'a')) {
                        fwrite($fp, "$aid\n");
                        fclose($fp);
                    } elseif($_G['adminid'] == 1) {
                        showmessage('view_log_invalid', '', array('logfile' => $_G['forum_logfile']));
                    }
                } else {
                    C::t('forum_attachment')->update_download($aid);
                }
            }

            $db = DB::object();
            $db->close();
            !$_G['config']['output']['gzip'] && ob_end_clean();


            if($attach['remote'] && !$_G['setting']['ftp']['hideurl'] && $isimage) {
                dheader('location:'.$_G['setting']['ftp']['attachurl'].'forum/'.$attach['attachment']);
            }

            $filesize = !$attach['remote'] ? filesize($filename) : $attach['filesize'];
            $attach['filename'] = '"'.(strtolower(CHARSET) == 'utf-8' && strexists($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? urlencode($attach['filename']) : $attach['filename']).'"';

            dheader('Date: '.gmdate('D, d M Y H:i:s', $attach['dateline']).' GMT');
            dheader('Last-Modified: '.gmdate('D, d M Y H:i:s', $attach['dateline']).' GMT');
            dheader('Content-Encoding: none');

            if($isimage && !empty($_GET['noupdate']) || !empty($_GET['request'])) {
                dheader('Content-Disposition: inline; filename='.$attach['filename']);
            } else {
                dheader('Content-Disposition: attachment; filename='.$attach['filename']);
            }
            if($isimage) {
                dheader('Content-Type: image');
            } else {
                dheader('Content-Type: application/octet-stream');
            }

            dheader('Content-Length: '.$filesize);

            $xsendfile = getglobal('config/download/xsendfile');

            if(!empty($xsendfile)) {
                $type = intval($xsendfile['type']);
                if($isimage){
                    $type = 0;
                }
                $cmd = '';
                switch ($type) {
                    case 1: $cmd = 'X-Accel-Redirect'; $url = $xsendfile['dir'].$attach['attachment']; break;
                    case 2: $cmd = $_SERVER['SERVER_SOFTWARE'] <'lighttpd/1.5' ? 'X-LIGHTTPD-send-file' : 'X-Sendfile'; $url = $filename; break;
                    case 3: $cmd = 'X-Sendfile'; $url = $filename; break;
                }
                if($cmd) {
                    dheader("$cmd: $url");
                    exit();
                }
            }

            if($readmod == 4) {
                dheader('Accept-Ranges: bytes');
                if(!empty($_SERVER['HTTP_RANGE'])) {
                    $rangesize = ($filesize - $range) > 0 ?  ($filesize - $range) : 0;
                    dheader('Content-Length: '.$rangesize);
                    dheader('HTTP/1.1 206 Partial Content');
                    dheader('Content-Range: bytes='.$range.'-'.($filesize-1).'/'.($filesize));
                }
            }

            $attach['remote'] ? getremotefile($attach['attachment']) : getlocalfile($filename, $readmod, $range);



        }

    }


}
if (!$_POST && $_GET['inf']) {
    include_once template("diy:common/header_ajax"); //头部
    function sc()
    {
        $ar = array();
        for ($i = 0; $i < 4; $i++) {
            $r = rand(0, 9);
            while (in_array($r, $ar)) $r = rand(0, 9);
            array_push($ar, $r);
        }
        return implode('', $ar);
    }


    $inf = $_GET['inf'];
    $inf = base64_decode($inf);
    $infos = explode("|", $inf);
    $mod = $infos[0];
    $aidencode = $infos[1];
    $ext = $infos[2];
    if ($infos[3] != 0)
        $filesize = (int)($infos[3] / 1024 + 1) . "kb";
    $downloads = $infos[4];
    $filename = urldecode($infos[5]);
    $need_pay = $infos[6];
    $pay_href = $infos[7];
    $a_id = $infos[8];
    $navtitle = $title;
    $uid = $_G['uid'];
    $free_txt='';
    $time1 = strtotime(date("Y-m-d",time()));
    $time2 = strtotime(date("Y-m-d",strtotime("+1 day")));
    $_need_pay = $need_pay;
    $is_free=0;
    $pay_count = C::t('#thinker_wx#common_attach_qrcode')->count_by_where("uid=$uid and  createtime>='{$time1}' and createtime<='{$time2}' and need_pay=1 and status=2");
    if (in_array($_G['groupid'], unserialize($splugin_setting['is_free_credits'])) && $need_pay && ($free_credits_limit != 0 && $pay_count < $free_credits_limit)) {
        $is_free = 1;
        $need_pay = 0;
        $free_txt=$is_free==1?' <font color=\'red\'>免吧币</font>' :'';
    }



    $time = time() - $qrcode_exprie;
    //C::t('#thinker_wx#common_attach_qrcode')->delete("uid=$uid and aid = $a_id and  createtime<='$time'");

    C::t('#thinker_wx#common_attach_qrcode')->update_by_where(array('status' => 1), "uid=$uid and aid = $a_id and  createtime<='$time'");
    $row = C::t('#thinker_wx#common_attach_qrcode')->fetch("uid=$uid and aid = $a_id and status=0 and createtime > '$time'");
    if (!$row) {
        $code1 = sc();
        $code2 = sc();
        $insertData = array();
        $insertData['uid'] = $uid;
        $insertData['aid'] = $a_id;
        $insertData['code1'] = $code1;
        $insertData['code2'] = $code2;
        $insertData['need_pay'] = $_need_pay;
        $insertData['createtime'] = time();
        C::t('#thinker_wx#common_attach_qrcode')->insert($insertData);
    } else {
        $code1 = $row['code1'];
        $code2 = $row['code2'];
    }
    $siteurl = $_G['siteurl'];
    echo <<<EOT
<form action="plugin.php?id=thinker_wx:qrcode" method="post" id="qrcode_form"  onsubmit="ajaxpost('qrcode_form','return_transfercredit');return false;">
<h3 class="flb" id="fctrl_attachpay" style="cursor: move;">
<em id="return_attachpay" fwin="attachpay">扫二维码关注微信,发送 <font color='red'>$code1</font> 到公众号获取验证码</em>
<span>
<a href="javascript:;" class="flbc" onclick="hideWindow('test')" title="关闭">关闭</a></span>
</h3>
<div class='c floatwrap'>
<div class='flb' style='font-size:16px;color:#999'><input type="hidden" value="$pay_href" name="payUrl"/>
<input type="hidden" value="$need_pay" name="need_pay"/>
<input type="hidden" value="$is_free" name="is_free"/>
<input type="hidden" value="$uid" name="uid"/><input type="hidden" value="$a_id" name="a_id"/><input type="hidden" value="$code1" name="code1"/>
验证码 : <input style='width:220px;border:1px solid #ccc;line-height:25px' name='code2' type='text' />
</div>
<div style='margin:5px auto;width:200px'><img  width='200' src='{$splugin_setting['wx_logo']}'/></div>
<p style="text-align:center">在上方输入验证码,验证正确后,你将可以{$free_txt}下载该附件! </p>
</div>
<input type='hidden' name='handlekey' value='transfercredit' />

<span style='display:none' id='return_transfercredit'></span>
<div style='margin:5px auto;width:50px'>
<button type="submit" name="replysubmit" id="fastpostsubmit" class="pn pnc vm" value="replysubmit" tabindex="5"><strong>提交</strong></button></div>
</form>

EOT;
    include_once template("diy:common/footer_ajax"); //尾部\


}

